/**
 * 针对表单数据的校验Javascript代码生成
 */
package aorey.database.config;

import aorey.config.FrameworkConfig;
import aorey.database.DataBaseFactory;
import aorey.database.DataCheck;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import aorey.database.DataTag;
import aorey.database.DataType;
import aorey.nosql.EhcacheUtil;
import java.util.ArrayList;

public class DataConfigForm {

    protected EhcacheUtil framework;
    protected HttpServletRequest request;

    public DataConfigForm(HttpServletRequest request,EhcacheUtil framework) {
    	this.framework = framework;
        this.request = request;
    }

    /**
     * 生成验证表单提交的js
     *
     * @param id
     * @return
     * @throws DocumentException
     */
    public String jsCheckForm(String id, boolean update) throws DocumentException {
        String configFile ;
        DataCheck dataCheck = new DataCheck();
        HashMap<String, DataType> dType = dataCheck.getDataType(FrameworkConfig.dataTypeConfig);
//        dType.getDataType("");
        if (update) {
            configFile = FrameworkConfig.updateConfig + "/" + id + ".xml";
        }
        else
        {
            configFile = FrameworkConfig.insertConfig + "/" + id + ".xml";
        }      
        
        File config = new java.io.File(configFile);
        StringBuilder jsCode = new StringBuilder();
        StringBuilder jsInsertForm = new StringBuilder();
        HashMap<String, String> formField = new HashMap<>();
        
        if (config.exists()) {
            SAXReader reader = new SAXReader();
            Document document = reader.read(config);
            Element root = document.getRootElement();
            Element table = root.elements().get(0);
            List<Element> fields = root.elements().get(0).elements();
            List<String> dbField = new ArrayList<>();
            List<String> xmlName = new ArrayList<>();
            StringBuilder selectField = new StringBuilder();
            int size = fields.size();
            String fieldID = "";
            String type = "";
            boolean allow_null = true;
            String errorText = "";
            String name = "";
            int len = 0;
            jsCode.append("function check_form_js(url) {try{var data = new Object();var flag = false;");

            for (int i = 0; i < size; i++) {
                // 在配置中id,type,errortext必填
                fieldID = fields.get(i).attributeValue("id");
                xmlName.add(fieldID);
                name = fields.get(i).attributeValue("name");
                dbField.add(name);
                // 计算修改数据时候的sql语句中的字段值
                if (update) {
                    if (i>0) {
                        selectField.append(",");
                    }
                    selectField.append(name);
                }         
                
                type = fields.get(i).attributeValue("type");
                errorText = fields.get(i).attributeValue("errortext");
                formField.put(name, fieldID);
                // 配置中选填项目
                try {
                    len = Integer.parseInt(fields.get(i).attributeValue("len"));
                } catch (Exception e) {
                    len = 0;
                }
                try 
                {
                    if (fields.get(i).attributeValue("null").equals("no")) {
                        allow_null = false;
                    } else {
                        allow_null = true;
                    }
                } 
                catch (Exception e) 
                {
                    allow_null = false;
                }

                jsCode.append("var ").append(fieldID).append("=$('#").append(fieldID).append("').val();");
                if (allow_null == false) {
                    jsCode.append("if(").append(fieldID).append(" == ''){show_msg('").append(fieldID).append("','").append(errorText).append("');return false;}");
                }
                jsCode.append("var reg = /").append(dType.get(type).reg).append("/;if(").append(fieldID).append(" !='' && !reg.test(").append(fieldID).append(")){show_msg('").append(fieldID).append("','").append(errorText).append("');return false;}");
                jsCode.append("data.").append(fieldID).append("=").append(fieldID).append(";");
            }
            
            // 如果是修改数据，需要读取源数据，并且填充到表单中
            if (update) 
            {
                String tabName = table.attributeValue("name");
                String where = table.attributeValue("where");
                String data_source = table.attributeValue("data_source");
                StringBuilder sql = new StringBuilder();
                sql.append("select ").append(selectField);
                sql.append(" from ").append(tabName);
                if (!where.equals("") || where!=null)
                {
                    sql.append(" where ").append(where);
                }   
                DataTag dataTag = new DataTag(request);
                String selectSQL = dataTag.tagReplace(sql.toString());
                DataBaseFactory dataBaseFactory = new DataBaseFactory();
                try {
//                    dataBaseFactory.getConnection(get(data_source).getConnection());
                	@SuppressWarnings("unchecked")
					HashMap<String, DataSource> dataBaseDrivers = (HashMap<String, DataSource>) framework.get("database", "drivers");
                	dataBaseFactory.getConnection(dataBaseDrivers.get(data_source).getConnection());
                    String rs = dataBaseFactory.getResult(selectSQL);
                    System.out.println(rs);
                    int dataSize = dbField.size();
                    System.out.println(dataSize);
                    for(int j = 0 ;j < dataSize; j++)
                    {
                        jsInsertForm.append("setInputValueById('").append(xmlName.get(j).toString()).append("','").append(dataBaseFactory.getResultValue(rs, 0, dbField.get(j))).append("',0);");
                    }
                    dataBaseFactory.close();
                    System.out.println(dataSize);
                } 
                catch (Exception e) 
                {
//                    jsInsertForm.append("/** error:").append(e.getMessage()).append(" **/");
                }
            }
            
            jsCode.append("$.post(url, data, function(result) {on_ok(result);}, \"json\").error(function() {on_error();});");
            jsCode.append("}catch(e){alert(e);}}");
        } else {
            jsCode.append("/** error: Can not find config. **/");
        }

        StringBuilder result = new StringBuilder();
        result.append(jsCode.toString());
        result.append(jsInsertForm.toString());
        return result.toString();
    }
}
